// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package watch_cmd

import (
	"fmt"
	"strings"

	"gitcode.com/openseaotter/so_proto_gen_go.git/watch_api"
	"gitcode.com/openseaotter/so_server/config"
	"gitcode.com/openseaotter/so_server/utils"
	"github.com/spf13/cobra"
)

var listCmd_Offset uint32
var listCmd_Limit uint32

var listCmd = &cobra.Command{
	Use: "list",
	RunE: func(cmd *cobra.Command, args []string) error {
		cfg, err := config.ReadServerConfig()
		if err != nil {
			return err
		}
		if cfg.SuperToken == "" {
			return fmt.Errorf("miss super token in config")
		}
		conn, err := utils.ConnGrpcServer(fmt.Sprintf("127.0.0.1:%d", cfg.ServicePort))
		if err != nil {
			return err
		}
		defer conn.Close()

		client := watch_api.NewWatchApiClient(conn)
		res, err := client.List(cmd.Context(), &watch_api.ListRequest{
			AccessToken: cfg.SuperToken,
			Offset:      listCmd_Offset,
			Limit:       listCmd_Limit,
		})

		if err != nil {
			return err
		}
		if res.Code != watch_api.ListResponse_CODE_OK {
			return fmt.Errorf("%s", res.ErrMsg)
		}
		fmt.Printf("total count %d offset %d limit %d\n", res.TotalCount, listCmd_Offset, listCmd_Limit)
		for _, info := range res.InfoList {
			fmt.Println("watchId:", info.WatchId)
			fmt.Println("secret:", info.Secret)
			fmt.Println("full image name list:", strings.Join(info.FullImageNameList, ","))
			fmt.Println("enable", info.Enable)
			fmt.Println("desc", info.Desc)
			fmt.Println("=========================================")
		}
		return nil
	},
}

func init() {
	listCmd.Flags().Uint32Var(&listCmd_Offset, "ofset", 0, "list watch offset")
	listCmd.Flags().Uint32Var(&listCmd_Limit, "limit", 10, "list watch limit")
}
